<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Upload;
use app\common\exception\UploadException;
use app\common\model\Attachment;
use OSS\Core\OssException;
use OSS\OssClient;
use think\addons\Controller;
use think\Config;
use think\Loader;


/**
 * 视频图片云存储
 */
class Multimediaoss extends Api {

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = '*';
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];
    
    public function _initialize() {

        parent::_initialize();
        // $this->config = Config::get('upload');
        if (!class_exists("\OSS\OssClient")) {
            //添加Alioss的命名空间
            Loader::addNamespace('OSS', ADDON_PATH . 'alioss' . DS . 'library' . DS . 'OSS' . DS);
        }
    }

    /**
     * [upload 视频上传]
     * @Author   Ming
     * @DateTime 2024-05-25
     * @param    [type]      [description]
     */
    public function videoUpload()
    {
        //默认普通上传文件
        $file = $this->request->file('file');
        if (!$file) {
            $this->error(__("No file upload"));
        }
        $attachment = null;
        try {
            $upload = new Upload($file);
            $attachment = $upload->videoUpload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

        //文件绝对路径
        $videoFilePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

        $videourl = $attachment->url;

        //返回视频第一帧
        $imagePath = '/uploads/'.date('Ymd').'/'.md5(microtime(true)).".jpg";
        $cmd =  "ffmpeg6 -ss 00:00:01 -i {$_SERVER['DOCUMENT_ROOT']}{$attachment->url} -s 240x336 -vframes 1 {$_SERVER['DOCUMENT_ROOT']}{$imagePath}";
        //$cmd =  "ffmpeg -ss 00:00:01 -i {$_SERVER['DOCUMENT_ROOT']}{$attachment->url} -vframes 1 {$_SERVER['DOCUMENT_ROOT']}{$imagePath}";
        $cmd = iconv('UTF-8','GB2312', $cmd);
        shell_exec($cmd.' 2>&1');
        $imgFilePath = ROOT_PATH.'public'.$imagePath;
        try {
            //视频上传
            $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $videoFilePath);
            //图片上传
            $ret = $oss->uploadFile($config['bucket'], ltrim($imagePath,"/"), $imgFilePath);

            //成功不做任何操作
        } catch (\Exception $e) {
             $this->delFile($videoFilePath,'');
             $this->delFile($imgFilePath,'');
             $this->error("上传失败");
        }

        // $snapshot ='?x-oss-process=video/snapshot,t_0,f_jpg';
        $this->delFile($videoFilePath,'');
        $this->delFile($imgFilePath,'');
        // 删除附件表数据
        // \app\common\model\Attachment::where("url", "in", [$videoFilePath,$imgFilePath])->delete();
        // unset($upload);//解除图片的进程
        // @unlink($filePath);
        //$this->success(__('Uploaded successful'), ['url' => $videourl, 'fullurl'=>$config['cdnurl'].$videourl, 'imgurl'=>$imagePath, 'fullimgUrl' => $config['cdnurl'].$imagePath]);
        $this->success(__('Uploaded successful'), ['url' => $config['cdnurl'].$videourl, 'fullurl'=>$config['cdnurl'].$videourl, 'imgurl'=>$config['cdnurl'].$imagePath, 'fullimgUrl' => $config['cdnurl'].$imagePath]);

        //return;
    }
    
    /**
     * [imageUpload 图片上传]
     * @Author   Ming
     * @DateTime 2024-05-25
     * @param    [type]      [description]
     */
    public function imageUpload()
    {
        //默认普通上传文件
        $file = $this->request->file('file');
        if (!$file) {
            $this->error(__("No file upload"));
        }
        $attachment = null;
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        //文件绝对路径
        $imgFilePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

        $imageurl = $attachment->url;
        try {
            //图片上传
            $ret = $oss->uploadFile($config['bucket'], ltrim($imageurl,"/"), $imgFilePath);
            //成功不做任何操作
        } catch (\Exception $e) {
             $this->delFile($imgFilePath,'');
             $this->error("上传失败");
        }

        $this->success(__('Uploaded successful'), ['url' => $config['cdnurl'].$imageurl, 'fullurl' => $config['cdnurl'].$imageurl]);
        //$this->success(__('Uploaded successful'), ['url' => $imageurl, 'fullurl' => $config['cdnurl'].$imageurl]);
    }

    /**
     * [delFile 删除文件]
     * @Author   Ming
     * @DateTime 2024-05-25
     * @param    [type]      $path [description]
     * @param    [type]            [description]
     */
     private function delFile($filePath,$upload){
        if ($upload) {
            unset($upload);//解除图片的进程
        }
        @unlink($filePath);
     }

    /**
     * [deleteFile 删除云存储文件]
     * @Author   Ming
     * @DateTime 2024-05-25
     * @param    [type]      [description]
     */
    public function deleteFile()
    {
        $data = $this->request->post();
        if (!$data && !$data['videopath'] && !$data['imgpath']) {
            $this->error(__('Invalid parameters'));
        }

        $config = get_addon_config('alioss');
        $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        try {
            $ossClient->deleteObject($config['bucket'], ltrim($data['videopath'], '/'));
            $ossClient->deleteObject($config['bucket'], ltrim($data['imgpath'], '/'));
        } catch (\Exception $e) {
            $this->error(__("File delete fail"));
        }

       $this->success(__("File delete success")); 

    }
    
    /**
     * [delVideo 删除视频]
     * @Author   Ming
     * @DateTime 2024-05-25
     * @param    [type]      [description]
     */
    public function delVideo()
    {
        $video_id = $this->request->post("video");
        if(!$video_id){
            $this->error(__("no select video"));
        }
        
        // 查询视频详情
        $videoModel = new Video();
        $video = $videoModel::where(['id'=>$video_id])->find();
        if(!$video){
            $this->error(__("no select video"));
        }

        $config = get_addon_config('alioss');
        $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        try {
            $ossClient->deleteObject($config['bucket'], ltrim($video['videopath'], '/'));
            $ossClient->deleteObject($config['bucket'], ltrim($video['imgpath'], '/'));
            //成功不做任何操作
        } catch (\Exception $e) {
            $this->error(__("Video delete fail"));
        }
        // 删除附件表数据
        // \app\common\model\Attachment::where("url", "in", $paths)->delete();
        
        $result = $video->delete();
        if(!$result){
            $this->error(__("Video delete fail"));
        } else {
            $this->success(__("Video delete success"));
        }
    }

    /*
    protected function checkVideoSize()
    {
        preg_match('/([0-9\.]+)(\w+)/', $this->config['vidio_maxsize'], $matches);
        $size = $matches ? $matches[1] : $this->config['vidio_maxsize'];
        $type = $matches ? strtolower($matches[2]) : 'b';
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)($size * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0));
        if ($this->fileInfo['size'] > $size) {
            throw new UploadException(__('File is too big (%sMiB). Max filesize: %sMiB.',
                round($this->fileInfo['size'] / pow(1024, 2), 2),
                round($size / pow(1024, 2), 2)));
        }
    }*/

}
